/*
 *  This file is part of the Jikes RVM project (http://jikesrvm.org).
 *
 *  This file is licensed to You under the Eclipse Public License (EPL);
 *  You may not use this file except in compliance with the License. You
 *  may obtain a copy of the License at
 *
 *      http://www.opensource.org/licenses/eclipse-1.0.php
 *
 *  See the COPYRIGHT.txt file distributed with this work for information
 *  regarding copyright ownership.
 */
package org.mmtk.plan.compressor;

import org.mmtk.plan.TraceLocal;
import org.mmtk.plan.Trace;
import org.mmtk.policy.Space;
import org.mmtk.policy.compressor.CompressorMetadata;
import org.mmtk.policy.compressor.MarkCopySpace;
import org.mmtk.utility.Log;
import org.mmtk.vm.VM;

import org.vmmagic.pragma.*;
import org.vmmagic.unboxed.*;

/**
 * This class implements the core functionality for a transitive
 * closure over the heap graph.
 */
@Uninterruptible
public class CompressorTraceLocal extends TraceLocal {
  private boolean VERBOSE = false;

  /**
   * Constructor
   */
  public CompressorTraceLocal(Trace trace, boolean specialized) {
    super(specialized ? Compressor.SCAN_MARK : -1, trace);
  }

  /**
   * Constructor
   */
  public CompressorTraceLocal(Trace trace) {
    this(trace, true);
  }

  /****************************************************************************
   *
   * Externally visible Object processing and tracing
   */

  /**
   * Return true if <code>obj</code> is a live object.
   *
   * @param object The object in question
   * @return True if <code>obj</code> is a live object.
   */
  public boolean isLive(ObjectReference object) {
    if (object.isNull()) return false;
    if (Space.isInSpace(Compressor.MC0, object))
      return Compressor.hi ? Compressor.markCopySpace0.isLive(object) : true;
    if (Space.isInSpace(Compressor.MC1, object))
      return Compressor.hi ? true : Compressor.markCopySpace1.isLive(object);
    return super.isLive(object);
  }


  /**
   * This method is the core method during the trace of the object graph.
   * The role of this method is to:
   *
   * 1. Ensure the traced object is not collected.
   * 2. If this is the first visit to the object enqueue it to be scanned.
   * 3. Return the forwarded reference to the object.
   *
   * @param object The object to be traced.
   * @return The new reference to the same object instance.
   */
  @Inline
  public ObjectReference traceObject(ObjectReference object) {
    if (object.isNull())
      return object;
    if (Space.isInSpace(Compressor.MC0, object))
      return Compressor.markCopySpace0.traceMarkObject(this, object);
    if (Space.isInSpace(Compressor.MC1, object))
      return Compressor.markCopySpace1.traceMarkObject(this, object);
    return super.traceObject(object);
  }

  /**
   * Ensure that this object will not move for the rest of the GC.
   *
   * @param object The object that must not move
   * @return The new object, guaranteed stable for the rest of the GC.
   */
  @Inline
  public ObjectReference precopyObject(ObjectReference object) {
    if(VERBOSE) {
      Log.write("precopyObject ");
    }
    
    if (Space.isInSpace(Compressor.fromSpace().getDescriptor(), object)) {
      if (CompressorMetadata.testAndSetLiveBits(object)) {
       
        // TODO: If precopy returns many different objects, this will cause a leak.
        // Currently, Jikes RVM does not require many objects to be precopied.
        ObjectReference newObject = VM.objectModel.copy(object, Compressor.ALLOC_IMMORTAL);
        MarkCopySpace.setForwardingPointer(object, newObject);
        if(VERBOSE) {
          Log.write(" "); Log.write(object); Log.write(" ==> "); Log.write(newObject); 
          Log.writeln();
        }
        
        processNode(newObject);
        return newObject;
      }
      // Somebody else got to it first
      while (MarkCopySpace.getForwardingPointer(object).isNull());
      
      return MarkCopySpace.getForwardingPointer(object);
    }
    
    if(VERBOSE) {
      Log.writeln();
    }
    
    return super.precopyObject(object);
  }
  
  /**
   * Collectors that move objects <b>must</b> override this method.
   * It performs the deferred scanning of objects which are forwarded
   * during bootstrap of each copying collection.  Because of the
   * complexities of the collection bootstrap (such objects are
   * generally themselves gc-critical), the forwarding and scanning of
   * the objects must be dislocated.  It is an error for a non-moving
   * collector to call this method.
   *
   * @param object The forwarded object to be scanned
   */
  @Inline
  @Override
  // TODO: Why do we need this ?
//  protected void scanObject(ObjectReference object) {
//    super.scanObject(object);
//    
////    if(VERBOSE ) {
////      Log.write("[CompressorTraceLocal.scanObject] "); Log.write(object); Log.writeln();
////    }
//    
//    if (Space.isInSpace(Compressor.MC0, object))
//      Compressor.markCopySpace0.traceMarkObject(this, object);
//    if (Space.isInSpace(Compressor.MC1, object))
//      Compressor.markCopySpace1.traceMarkObject(this, object);
//  }

  /**
   * Will this object move from this point on, during the current trace ?
   *
   * @param object The object to query.
   * @return True if the object will not move.
   */
  public boolean willNotMoveInCurrentCollection(ObjectReference object) {
    // This trace only marks live objects and does not move anything
    //return false;
    
    if(VM.VERIFY_ASSERTIONS) {
      boolean cond1 = (Compressor.hi && !Space.isInSpace(Compressor.MC0, object)) ||
                      (!Compressor.hi && !Space.isInSpace(Compressor.MC1, object));
      boolean cond2 = !Space.isInSpace(Compressor.fromSpace().getDescriptor(), object);
      VM.assertions._assert(cond1 == cond2);
    }
    return !Space.isInSpace(Compressor.fromSpace().getDescriptor(), object);
  }
  
}


